package com.bulletelc.apollopre.module.user.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.eventbus.LoginEvent;
import com.bulletelc.apollopre.eventbus.WeChatEntryEventBus;
import com.bulletelc.apollopre.framework.MVPBaseFragment;
import com.bulletelc.apollopre.module.main.center.setting.activity.SmsVerifyActivity;
import com.bulletelc.apollopre.module.user.LoginMainActivity;
import com.bulletelc.apollopre.module.user.register.RegisterActivity;
import com.bulletelc.apollopre.utils.RegExUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by CX on 2018/3/29.
 */

public class LoginFragment extends MVPBaseFragment<LoginContract.View, LoginPresenter> implements LoginContract.View,
        View.OnClickListener {

    private EditText etMobile;
    private EditText etPassword;
    private Button btnLogin;
    private Button btnQuickRegister;
    private Button btnForgetPassword;
    private ImageView ivWxEntry;

    public static LoginFragment getInstance() {
        LoginFragment fragment = new LoginFragment();
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public int getLayoutRes() {
        return R.layout.login_fragment;
    }

    @Override
    public void assignViews() {
        etMobile = findView(R.id.etMobile);
        etPassword = findView(R.id.etPassword);
        btnLogin = findView(R.id.btnLogin);
        btnQuickRegister = findView(R.id.btnQuickRegister);
        btnForgetPassword = findView(R.id.btnForgetPassword);
        ivWxEntry = findView(R.id.ivWxEntry);
    }

    @Override
    public void setListener() {
        btnLogin.setOnClickListener(this);
        btnQuickRegister.setOnClickListener(this);
        btnForgetPassword.setOnClickListener(this);
        ivWxEntry.setOnClickListener(this);

    }

    @Override
    public void initData(Bundle savedInstanceState) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnLogin:
                if (getActivity() instanceof checkPermission) {
                    ((checkPermission) getActivity()).checkPermission();
                }
                break;

            case R.id.btnQuickRegister:
                String unionid = ((LoginMainActivity) getActivity()).getUnionid();
                Intent intentReg = new Intent(getContext(), RegisterActivity.class);
                if (null != unionid) {
                    intentReg.putExtra(IntentCode.EXTRA_FORM_TYPE, 2);
                    intentReg.putExtra(IntentCode.EXTRA_UNIONID, unionid);
                }
                startActivity(intentReg);
                break;

            case R.id.btnForgetPassword:
                //todo 跳转到忘记密码界面
                Intent intentPaw = new Intent(getContext(), SmsVerifyActivity.class);
                startActivity(intentPaw);
                break;
            case R.id.ivWxEntry:
                wechatLogin();
                break;
        }
    }

    @Override
    public void success() {
        presenter.getSetting();
    }

    @Override
    public void fail(String fail) {
        ToastUtil.showLongToast(getContext(), fail);
    }

    @Override
    public void error(String error) {
        ToastUtil.showLongToast(getContext(), R.string.network_msg);
    }

    @Override
    public void onSuccessGetSetting() {
        Toast.makeText(getContext(), getString(R.string.toast_login_success), Toast.LENGTH_SHORT).show();
        if (getActivity() instanceof iFinish) {
            ((iFinish) getActivity()).ifinish();
        }
    }

    @Override
    public void onFailGetSetting(String fail) {
        ToastUtil.showLongToast(getContext(), fail);
    }

    @Override
    public void onErrorGetSetting(String error) {
        ToastUtil.showLongToast(getContext(), R.string.network_msg);
    }

    @Override
    public void onSuccessWeChatEntry(String unionid) {
        if (!"".equals(unionid) && null != unionid) {
            ((LoginMainActivity)getActivity()).setUnionid(unionid);
            ToastUtil.showLongToast(baseActivity, R.string.wx_entry_bind);
        }

    }

    @Override
    public void onErrorWeChatEntry(String error) {
        ToastUtil.showLongToast(getContext(), R.string.network_msg);
    }

    @Override
    public void onFailWeChatEntry(String fail) {
        ToastUtil.showLongToast(getContext(), fail);
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(LoginEvent event) {
        String mobile = etMobile.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String unionid = ((LoginMainActivity) getActivity()).getUnionid();
        if (!RegExUtil.isMobileExact(mobile)) {
            etMobile.setError(getString(R.string.hint_input_correct_mobile));
            return;
        }

        if (password == null || password.length() < 6) {
            etPassword.setError(getString(R.string.hint_input_six_password));
            return;
        }

        presenter.login(mobile, password, "android001", unionid);
    }

    /**
     * 接受微信授权处理事件
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WeChatEntryEventBus event) {
        BaseResp baseResp = event.getBaseResp();
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                ToastUtil.showShortToast(baseActivity, "取消操作");
                break;
            case BaseResp.ErrCode.ERR_OK:
                switch (baseResp.getType()) {
                    case 1: //登陆微信
                        //拿到了微信返回的code,立马再去请求access_token
                        String code = ((SendAuth.Resp) baseResp).code;
                        //请求自己服务器换取用户信息,get请求
                        presenter.weChatEntry(code);
                        //getAccessToken(code);
                        break;
                }
                break;
        }
    }

    /**
     * 检查权限接口
     */
    public interface checkPermission {
        void checkPermission();
    }

    /**
     * 销毁Activity界面
     */
    public interface iFinish {
        void ifinish();
    }

    /**
     * 调出微信授权Activity
     */
    public void wechatLogin() {
        if (!MyApplication.iwxapi.isWXAppInstalled()) {
            ToastUtil.showShortToast(baseActivity, "您还没安装微信客户端");
        }
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "diandi_wx_login";
        MyApplication.iwxapi.sendReq(req);
    }
}
